/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aypuyprueba;

import BESA.ExceptionBESA;
import BESA.Kernel.Agent.Event.EventBESA;
import BESA.Kernel.Agent.KernellAgentExceptionBESA;
import BESA.Kernel.System.AdmBESA;
import BESA.Kernel.System.Directory.AgHandlerBESA;
import aypuyprueba.agent.AgentTest;
import aypuyprueba.guard.SMA_ReceiveHandlerAYPUY;
import aypuy.directorymanager.agent.DirectoryAgentAYPUY;
import aypuy.directorymanager.agent.data.DIRDirectoryManagementData;
import aypuy.directorymanager.agent.guards.DIR_RegisterLogicalManagerAYPUY;
import aypuy.logicalmgr.agent.LogicalManagerAgentAYPUY;
import aypuy.logicalmgr.agent.data.LMRegisterPhysicalManagerData;
import aypuy.logicalmgr.agent.guards.LM_RegisterPhysicalAgentAYPUY;
import aypuy.logicalmgr.agent.logicalregistry.FileDescriptionAYPUY;
import aypuy.physicalmgr.agent.PhysicalManagerAgentAYPUY;
import aypuy.workspacemgr.agent.WorkSpaceManagerAgentAYPUY;
import aypuy.workspacemgr.agent.data.RoleManagementDataAYPUY;
import aypuy.workspacemgr.agent.data.WSManagementDataAYPUY;
import aypuy.workspacemgr.agent.data.WSManageResourceDataAYPUY;
import aypuy.workspacemgr.agent.guards.WSM_ManagementGuardAYPUY;
import aypuy.workspacemgr.agent.guards.WSM_ResourceREQGuardAYPUY;
import aypuy.workspacemgr.workspace.WorkSpaceAYPUY;
import java.awt.HeadlessException;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.BitSet;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/**
 *
 * @author Ayllu
 */
public class CompleteTest {

    private static AdmBESA admLocal;
    private static Properties props;
    
    public static void main(String[] args) {
         String rootDirectory=null;
         String fileToSend;
        try {
            admLocal = AdmBESA.getInstance();
            props = new Properties();
            props.load(new FileInputStream("aypuyConfig.properties"));
            AgentTest test = new AgentTest("Alias1", 0.91);

            test.start();
            createDirectory();
            createWorkSpaceManager();
            createLogicalAgents();
            rootDirectory = showChooser(rootDirectory,true)+"\\";
            createPhysicalAgents(rootDirectory);

            BitSet elbitBitSet = new BitSet();
            elbitBitSet.set(0);
            //elbitBitSet.set(3);
            elbitBitSet.set(1);
            elbitBitSet.set(4);
            AgHandlerBESA hand = admLocal.getHandlerByAlias(props.getProperty("wsmanageralias"));
            /**
             * |||||||||Inserción Recurso||||||||||||
             */
            fileToSend=showChooser(rootDirectory,false);
            Logger.getLogger(CompleteTest.class.getName()).log(Level.INFO,"Inicio Insercion recurso");
            WSManageResourceDataAYPUY dtaIns = new WSManageResourceDataAYPUY(SMA_ReceiveHandlerAYPUY.class.getName(),test.getAid(), WorkSpaceAYPUY.UPDATE, elbitBitSet, "USUARIO", "Son2", new FileDescriptionAYPUY("Recurso", fileToSend));
            EventBESA evIns = new EventBESA(WSM_ResourceREQGuardAYPUY.class.getName(), dtaIns);
            hand.sendEvent(evIns);

            Logger.getLogger(CompleteTest.class.getName()).log(Level.INFO,"Fin Insercion Recurso");

            /**
             * |||||||||Solicitud Recurso||||||||||||
             */
            
            WSManageResourceDataAYPUY dtaReq = new WSManageResourceDataAYPUY(SMA_ReceiveHandlerAYPUY.class.getName(),test.getAid(), WorkSpaceAYPUY.RETRIEVE, elbitBitSet, "USUARIO", "Son3", "Recurso");
            EventBESA evreq = new EventBESA(WSM_ResourceREQGuardAYPUY.class.getName(), dtaReq);
            hand.sendEvent(evreq);
            Thread.sleep(1000);
            admLocal.kill(0.91);
            Logger.getLogger(CompleteTest.class.getName()).log(Level.INFO,"Fin Solicitud Recurso!");
            
            //System.exit(0);
        }catch (IOException ioex){
            Logger.getLogger(CompleteTest.class.getName()).log(Level.SEVERE, null, ioex);
        } catch (InterruptedException ex) {
            Logger.getLogger(CompleteTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExceptionBESA ex) {
            Logger.getLogger(CompleteTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static String showChooser(String rootDirectory, boolean directoryOnly) throws HeadlessException {
        JFileChooser chooser = new JFileChooser(rootDirectory);
        if(directoryOnly){
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        }else {
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        }
        int returnVal = chooser.showOpenDialog(new JFrame());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            if(directoryOnly){
                rootDirectory=chooser.getSelectedFile().getAbsolutePath();
            }else{
                rootDirectory=chooser.getSelectedFile().getName();
            }
        }
        return rootDirectory;
    }

    private static void createWorkSpaceManager() throws ExceptionBESA {
        WorkSpaceManagerAgentAYPUY manager = new WorkSpaceManagerAgentAYPUY(props.getProperty("wsmanageralias"), 0.91);
        manager.start();

        AgHandlerBESA handler = admLocal.getHandlerByAid(manager.getAid());

        RoleManagementDataAYPUY rolemgmt;
        WSManagementDataAYPUY wsmgmt;

        wsmgmt = new WSManagementDataAYPUY("Father", WSManagementDataAYPUY.EnumWSMgmtAYPUY.CREATE_ROOTWS);
        EventBESA ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), wsmgmt);
        handler.sendEvent(ev);

        /**
         * createRootWorkSpace("Father");
         */
        wsmgmt = new WSManagementDataAYPUY("Son", "Father");
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), wsmgmt);
        handler.sendEvent(ev);
        /**
         * createWorkSpace("Son", "Father");
         */
        wsmgmt = new WSManagementDataAYPUY("Son2", "Son");
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), wsmgmt);
        handler.sendEvent(ev);
        /**
         * createWorkSpace("Son2", "Son");
         */
        wsmgmt = new WSManagementDataAYPUY("Son3", "Son2");
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), wsmgmt);
        handler.sendEvent(ev);
        /**
         * createWorkSpace("Son3", "Son2");
         */
        rolemgmt = new RoleManagementDataAYPUY("USUARIO", "Son", RoleManagementDataAYPUY.EnumRoleMgmtAYPUY.ADD_ROLE);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), rolemgmt);
        handler.sendEvent(ev);
        /**
         * addRoleToWorkspace("Son","USUARIO");
         */
        rolemgmt = new RoleManagementDataAYPUY("PROFESOR", "Son", RoleManagementDataAYPUY.EnumRoleMgmtAYPUY.ADD_ROLE);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), rolemgmt);
        handler.sendEvent(ev);
        /**
         * addRoleToWorkspace("Son","PROFESOR");
         */
        rolemgmt = new RoleManagementDataAYPUY("USUARIO", "Son2", RoleManagementDataAYPUY.EnumRoleMgmtAYPUY.ADD_ROLE);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), rolemgmt);
        handler.sendEvent(ev);
        /**
         * addRoleToWorkspace("Son2","USUARIO") //aqui al crear un nuevo usuario
         * se crea con permisos false, lo que sobreescribe el son
         */
        rolemgmt = new RoleManagementDataAYPUY("USUARIO", "Son", RoleManagementDataAYPUY.EnumRoleMgmtAYPUY.ADD_PERM, WorkSpaceAYPUY.UPDATE, WorkSpaceAYPUY.RETRIEVE);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), rolemgmt);
        handler.sendEvent(ev);
        /**
         * addPermission("Son", "USUARIO", new
         * int[]{WorkSpaceAYPUY.UPDATE,WorkSpaceAYPUY.RETRIEVE});
         */
        rolemgmt = new RoleManagementDataAYPUY("PROFESOR", "Son", RoleManagementDataAYPUY.EnumRoleMgmtAYPUY.ADALL_PERM);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), rolemgmt);
        handler.sendEvent(ev);
        /**
         * addAllPermissions("Son", "PROFESOR");
         */
        wsmgmt = new WSManagementDataAYPUY("Son3", WSManagementDataAYPUY.EnumWSMgmtAYPUY.PRINTWS);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), wsmgmt);
        handler.sendEvent(ev);
        /**
         * printWorkspace("Son3");
         */
        rolemgmt = new RoleManagementDataAYPUY("USUARIO", "Son3", RoleManagementDataAYPUY.EnumRoleMgmtAYPUY.HAS_PERM, WorkSpaceAYPUY.UPDATE);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), rolemgmt);
        handler.sendEvent(ev);
        /**
         * hasPermission("Son3","USUARIO", WorkSpaceAYPUY.UPDATE)
         */
        rolemgmt = new RoleManagementDataAYPUY("USUARIO", "Son2", RoleManagementDataAYPUY.EnumRoleMgmtAYPUY.ADD_PERM, WorkSpaceAYPUY.UPDATE);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), rolemgmt);
        handler.sendEvent(ev);
        /**
         * addPermission("Son2","USUARIO", new int[]{WorkSpaceAYPUY.UPDATE});
         */
        wsmgmt = new WSManagementDataAYPUY("Son3", WSManagementDataAYPUY.EnumWSMgmtAYPUY.PRINTWS);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), wsmgmt);
        handler.sendEvent(ev);
        /*
         * printWorkspace("Son3");
         */
        rolemgmt = new RoleManagementDataAYPUY("USUARIO", "Son3", RoleManagementDataAYPUY.EnumRoleMgmtAYPUY.HAS_PERM, WorkSpaceAYPUY.UPDATE);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), rolemgmt);
        handler.sendEvent(ev);
        /**
         * hasPermission("Son3","USUARIO", WorkSpaceAYPUY.UPDATE)
         */
        rolemgmt = new RoleManagementDataAYPUY("USUARIO", "Son2", RoleManagementDataAYPUY.EnumRoleMgmtAYPUY.ADD_PERM, WorkSpaceAYPUY.RETRIEVE);
        ev = new EventBESA(WSM_ManagementGuardAYPUY.class.getName(), rolemgmt);
        handler.sendEvent(ev);
    }

    private static void createDirectory() throws ExceptionBESA, InterruptedException {
        DirectoryAgentAYPUY directory = new DirectoryAgentAYPUY(props.getProperty("directoryalias"), 0.91);
        directory.start();
    }

     private static void createLogicalAgents() {
        BitSet abitset = new BitSet();
        abitset.set(0);
        abitset.set(1);
        String nombres[] = new String[]{"LogAg1", "LogAg2", "LogAg3", "LogAg4"};
        for (String nom : nombres) {
            try {
                new LogicalManagerAgentAYPUY(nom, abitset, 0.91).start();
            } catch (KernellAgentExceptionBESA ex) {
                Logger.getLogger(CompleteTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        abitset.clear();
        abitset.set(4);
        nombres = new String[]{"LogAg5", "LogAg6"};
        for (String nom2 : nombres) {
            try {
                new LogicalManagerAgentAYPUY(nom2, abitset, 0.91).start();
            } catch (KernellAgentExceptionBESA ex) {
                Logger.getLogger(CompleteTest.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            
            DIRDirectoryManagementData datamgmt = new DIRDirectoryManagementData(abitset, admLocal.getHandlerByAlias("LogAg3").getAgId());
            EventBESA event = new EventBESA(DIR_RegisterLogicalManagerAYPUY.class.getName(), datamgmt);

            admLocal.getHandlerByAlias(props.getProperty("directoryalias")).sendEvent(event);

            datamgmt = new DIRDirectoryManagementData(abitset, admLocal.getHandlerByAlias("LogAg4").getAgId());
            event = new EventBESA(DIR_RegisterLogicalManagerAYPUY.class.getName(), datamgmt);

            admLocal.getHandlerByAlias(props.getProperty("directoryalias")).sendEvent(event);
        } catch (ExceptionBESA ex) {
            Logger.getLogger(LogicalManagerAgentAYPUY.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static void createPhysicalAgents(String rootFolder) {
        try {
            PhysicalManagerAgentAYPUY pagent = new PhysicalManagerAgentAYPUY("PM_a1", rootFolder, 0.91);
            pagent.start();
            PhysicalManagerAgentAYPUY pagent2 = new PhysicalManagerAgentAYPUY("PM_a2", rootFolder, 0.91);
            pagent2.start();

            LMRegisterPhysicalManagerData reg = new LMRegisterPhysicalManagerData(pagent.getAid());
            EventBESA eventreg = new EventBESA(LM_RegisterPhysicalAgentAYPUY.class.getName(), reg);
            admLocal.getHandlerByAlias("LogAg3").sendEvent(eventreg);

            reg = new LMRegisterPhysicalManagerData(pagent2.getAid());
            eventreg = new EventBESA(LM_RegisterPhysicalAgentAYPUY.class.getName(), reg);
            admLocal.getHandlerByAlias("LogAg4").sendEvent(eventreg);

        } catch (KernellAgentExceptionBESA ex) {
            Logger.getLogger(CompleteTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExceptionBESA ex) {
            Logger.getLogger(CompleteTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
